<template>
  <el-header style="height: 150px">
    <el-row style="font-family: cursive">
      <span v-if="!adminName">
        免费<router-link to="/register">注册</router-link>,请登录(<router-link
          to="/login"
          >普通用户登录</router-link
        >/<router-link to="/login2">管理员登录</router-link>)
      </span>
      <span v-else>
        欢迎你管理员,{{ adminName }},
        <a href="" @click.prevent="deleteUser">退出登录</a> <!-- .prevent阻止默认行为-->
      </span>
    </el-row>
    <hr />
    <el-row style="width: 100%; background-color: #c4d7ea">
      <el-col :span="1">
        <img
          src="../assets/images/NO1.jpg"
          alt=""
          style="margin: 30px 30px; width: 70px; height: 70px"
      /></el-col>
      <el-col :span="19"
        ><h2
          style="
            color: #4f7298;
            font-family: cursive;
            font-size: 30px;
            margin: 50px 30px;
          "
        >
          雅黛美妆海外免税购管理员系统
        </h2></el-col
      >
      <el-col :span="4" style="margin-top: 100px">
        <el-breadcrumb separator-class="el-icon-arrow-right"><!-- :to动态指定导航的路径或对象 -->
          <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/admin_add' }"
            >添加商品</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>

    <el-row id="bigrow">
      <!-- 侧边栏 -->
      <el-col style="width: 10%; height: 100%" class="tac">
        <el-menu
          :default-active="selectedMenu"
          @select="handleClick"
          style="height: 3800px"
          class="el-menu-vertical-demo"
          background-color="#7BA6D0"
          text-color="#fff"
          active-text-color="#ffd04b"
        ><!-- v-on绑定select事件-->
          <el-menu-item index="1">
            <i class="el-icon-location"></i>
            <span slot="title">商品管理</span>
            <!-- 管理商品增删改查-->
          </el-menu-item>
          <el-menu-item index="2">
            <i class="el-icon-menu"></i>
            <span slot="title">数据管理</span>
            <!-- 管理商品数据统计-->
          </el-menu-item>
          <el-menu-item index="3">
            <i class="el-icon-menu"></i>
            <span slot="title">订单管理</span>
            <!-- 管理发货-->
          </el-menu-item>
          <el-menu-item index="4">
            <i class="el-icon-setting"></i>
            <span slot="title">用户管理</span>
            <!-- 查看所有用户信息-->
          </el-menu-item>
        </el-menu>
      </el-col>

      <el-col id="col" v-if="selectedMenu === '1'">
        <el-row id="col-row">
          <span style="margin: auto">商品展示</span>
        </el-row>
        <!-- 购物车表格 -->
        <el-table :data="accounts2">
          <!-- 商品编号 -->
          <el-table-column
            label="编号"
            type="index"
            align="center"
            width="100"
          ></el-table-column>
          <!-- 商品名称 --><!--prop该列对应的数据对象中的字段名，lable该列的表头文字-->
          <el-table-column
            prop="name"
            label="商品名称"
            align="center"
          >
        </el-table-column>
          <!-- 商品图片 -->
          <el-table-column prop="img" label="商品图片" align="center">
            <!--scope 对象包含了当前行的数据和索引。 -->
            <template slot-scope="scope">
              <!--图片路径拼接 -->
              <img
                :src="'http://127.0.0.1:3001/images/' + scope.row.img"
                alt=""
                style="width: 50px; height: 50px"
               />

            </template>
          </el-table-column>
          <!-- 商品编号 -->
          <el-table-column
            prop="totalnum"
            label="商品编号"
            align="center"
          ></el-table-column>
          <!-- 商品单价 -->
          <el-table-column prop="price" label="单价" align="center">
          </el-table-column>
          <!-- 商品描述 -->
          <el-table-column
            prop="msg"
            label="商品描述"
            align="center"
          ></el-table-column>
          <!-- 商品库存 -->
          <el-table-column prop="inventory" label="库存" align="center">
          </el-table-column>
          <!-- 商品分类cid -->
          <el-table-column prop="cid" label="商品分类cid" align="center">
          </el-table-column>
          <!-- 商品上下架状态 -->
          <el-table-column prop="shelves" label="上下架状态" align="center">
          </el-table-column>
          <!-- 商品操作 -->
          <el-table-column label="商品操作" align="center">
             <!-- template 标签来定义一个插槽，并将其命名为 slot-scope="scope"。表示使用一个作用域插槽，并且 scope 对象包含了当前行的数据和索引。 -->
            <template slot-scope="scope"><!-- 当前行的索引 (scope.$index) 和当前行的数据 (scope.row)。 -->
              <el-button
                size="mini"
                type="danger"
                @click="Onshelf(scope.$index, scope.row)"
              >
                上架
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="Offshelf(scope.$index, scope.row)"
                style="margin-top: 10px"
                >下架</el-button
              >·
              <el-button size="mini" @click="editgoods(scope.$index, scope.row)"
                style="margin-top:5px">修改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>

      <el-col id="col" v-if="selectedMenu === '2'">
        <el-row id="col-row">
          <span>数据统计</span>
        </el-row>
        <el-row id="col2-row3">
            <el-row id=echarts1>
              <!-- 商品 容器 --><!--ref：为模板中的某个元素或子组件创建一个唯一的引用标识符,通过 ref 引用子组件-->
              <div ref="goodEcharts" style="width: 100%; height: 100%"></div>
            </el-row>
            <el-row id=echarts2>
               <!-- 支付比 容器 -->
              <div ref="payEcharts" style="width: 100%; height: 100%"></div>
            </el-row>
            <el-row id=echarts3>
              <!-- 订单商品 容器 -->
              <div ref="orderEcharts" style="width: 100%; height: 100%"></div>
            </el-row>
          </el-row>
        <el-row id="col2-row2">
          <el-row id="col2-row2-cardrow">
            <div id="col-card" style="background-color: #faebeb">
              <el-row id="card1">销售额<hr/></el-row>
              <el-row id="card2">
                <el-col id="card3"><i class="el-icon-s-shop"></i></el-col>
                <el-col id="card4"
                  >{{ salestatistics[0]["sum(ordertotal)"] }} 元</el-col> <!-- 显示salestatistics数组的第一个元素的 "sum(ordertotal)"属性的值 -->
              </el-row>
            </div>
            <div id="col-card" style="background-color: #d8e9fa">
              <el-row id="card1"
                >已支付订单数
                <hr
              /></el-row>
              <el-row id="card2">
                <el-col id="card3"><i class="el-icon-success"></i></el-col>
                <el-col id="card4">{{ yizhifu[0]["count(*)"] }} 单</el-col>
              </el-row>
            </div>
            <div id="col-card" style="background-color: #e4def5">
              <el-row id="card1"
                >未支付订单数
                <hr
              /></el-row>
              <el-row id="card2">
                <el-col id="card3"><i class="el-icon-error"></i></el-col>
                <el-col id="card4">{{ weizhifu[0]["count(*)"] }} 单</el-col>
              </el-row>
            </div>
            <div id="col-card" style="background-color: #ccf1f7">
              <el-row id="card1"
                >用户数
                <hr
              /></el-row>
              <el-row id="card2">
                <el-col id="card3"><i class="el-icon-user-solid"></i></el-col>
                <el-col id="card4"
                  >{{ userstatistics[0]["count(*)"] }} 位</el-col
                >
              </el-row>
            </div>
          </el-row>


        </el-row>
      </el-col>

      <el-col id="col" v-if="selectedMenu === '3'">
        <el-row id="col-row">
          <span style="margin: auto">订单展示</span>
        </el-row>
        <!-- 下拉选择框 -->
        <el-select
          v-model="orderStatus"
          placeholder="请选择订单状态"
          style="width: 200px"
        >
          <el-option label="已支付订单" value="paid"></el-option>
          <el-option label="未支付订单" value="unpaid"></el-option>
        </el-select>
        <!-- 已支付订单 -->
        <el-table :data="trueorder" v-if="orderStatus === 'paid'">
          <!-- 编号 -->
          <el-table-column
            label="编号"
            type="index"
            align="center"
            width="100"
          ></el-table-column>
          <!-- 订单号 -->
          <el-table-column
            prop="ordernum"
            label="订单号"
            align="center"
          ></el-table-column>
          <!-- 买家 -->
          <el-table-column
            prop="nickname"
            label="买家"
            align="center"
          ></el-table-column>
          <!-- 商品信息 -->
          <el-table-column prop="name" label="商品信息" align="center"
            ><template slot-scope="scope">
              <div
                v-for="(name, index) in scope.row.goods_names.split(',')" :key="index"> <!-- :key="index" 强制Vue重新渲染表格组件,就不会出现一闪一闪的情况-->
                 <!-- goods_names.split(',') 将从后端返回的合并后的商品名称字符串拆分为数组，然后使用 v-for 循环显示每个商品。 -->
                {{ name }}
              </div>
             
            </template></el-table-column>
          <!-- 订单总价 -->
          <el-table-column prop="ordertotal" label="订单总价" align="center"><!-- prop显示ordertotal这个数据字段的值。 -->
          </el-table-column>
          <!-- 下单时间 -->
          <el-table-column prop="ordertime" label="下单时间" align="center">
          </el-table-column>
          <!-- 发货状态 -->
          <el-table-column
            prop="sendoutGoods"
            label="发货状态"
            align="center"
          ></el-table-column>
          <!-- 操作 -->
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                :disabled="scope.row.sendoutGoods === '已发货'"
                @click="goshipments(scope.$index, scope.row)"><!-- 当前行的索引 (scope.$index) 和当前行的数据 (scope.row)。 -->
                {{
                  scope.row.sendoutGoods === "已发货" ? "商品已发货" : "去发货"
                }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 未支付订单 -->
        <el-table :data="falseorder" v-if="orderStatus === 'unpaid'">
          <!-- 商品编号 -->
          <el-table-column
            label="编号"
            type="index"
            align="center"
            width="100"
          ></el-table-column>
          <!-- 订单号 -->
          <el-table-column
            prop="ordernum"
            label="订单号"
            align="center"
          ></el-table-column>
          <!-- 买家 -->
          <el-table-column
            prop="nickname"
            label="买家"
            align="center"
          ></el-table-column>
          <!-- 商品信息 -->
          <el-table-column prop="name" label="商品信息" align="center">
            <template slot-scope="scope">
              <div
                v-for="(name, index) in scope.row.goods_names.split(',')"
                :key="index"> 
                 <!-- goods_names.split(',') 将从后端返回的合并后的商品名称字符串拆分为数组，然后使用 v-for 循环显示每个商品。 -->
                {{ name }}
              </div>
            </template>
          </el-table-column>
          <!-- 订单总价 -->
          <el-table-column prop="ordertotal" label="订单总价" align="center">
          </el-table-column>
          <!-- 下单时间 -->
          <el-table-column prop="ordertime" label="下单时间" align="center">
          </el-table-column>
          <!-- 支付状态 -->
          <el-table-column prop="pricestatus" label="支付状态" align="center">
          </el-table-column>
          <!-- 联系方式 -->
          <el-table-column prop="phone" label="联系方式" align="center">
          </el-table-column>
        </el-table>
      </el-col>

      <el-col id="col" v-if="selectedMenu === '4'">
        <el-row id="col-row">
          <span style="margin: auto">用户展示</span>
        </el-row>
        <el-row>
          <!-- 用户表格 -->
          <el-table :data="alluser">
            <!-- 商品编号 -->
            <el-table-column
              label="编号"
              type="index"
              align="center"
              width="100"
            ></el-table-column>
            <!-- 用户名 -->
            <el-table-column
              prop="username"
              label="用户名"
              align="center"
            ></el-table-column>
            <!-- 用户昵称 -->
            <el-table-column
              prop="nickname"
              label="用户昵称"
              align="center"
            ></el-table-column>
            <!-- 电话 -->
            <el-table-column prop="phone" label="电话" align="center">
            </el-table-column>
            <!-- 收货地址 -->
            <el-table-column
              prop="address"
              label="收货地址"
              align="center"
            ></el-table-column>
          </el-table>
        </el-row>
      </el-col>
    </el-row>
  </el-header>
</template>

<script>
import HeaderCart from "../components/HeaderCart.vue";
import HeaderSearch from "../components/HeaderSearch.vue";
import * as echarts from "echarts";
export default {
  name: "Admin",
  data() {
    return {
      selectedMenu: "1", //初始化值为1
      adminName: "", // 从sessionStorage中获取管理员用户名
      orderStatus: "paid", // 默认显示已支付订单
      accounts2: [],
      alluser: [],
      trueorder: [],
      falseorder: [],
      //  统计
      salestatistics: [], //销售额
      yizhifu: [], //已支付订单数量
      weizhifu: [], //未支付订单数量
      userstatistics: [], //用户数量
      echone: [], //各分类商品数量
      echtwo: [],
      echthree: [],
    };
  },
  created() {
    this.adminName = sessionStorage.getItem("adminName");
    this.axios //展示所有商品
      .post("/api/admin/showgoods", {})
      .then((response) => {
        console.log("成功发送请求");
        this.accounts2 = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //展示所有用户
      .post("/api/admin/showusers", {})
      .then((response) => {
        console.log("成功发送请求");
        this.alluser = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //展示所有已支付商品
      .post("/api/admin/showtrueorder", {})
      .then((response) => {
        console.log("成功发送请求");
        this.trueorder = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //展示所有未支付商品
      .post("/api/admin/showfalseorder", {})
      .then((response) => {
        console.log("成功发送请求");
        this.falseorder = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //销售额
      .post("/api/admin/salestatistics", {})
      .then((response) => {
        console.log("成功发送请求");
        this.salestatistics = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //已支付订单数
      .post("/api/admin/yizhifu", {})
      .then((response) => {
        console.log("成功发送请求");
        this.yizhifu = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //未支付订单数
      .post("/api/admin/weizhifu", {})
      .then((response) => {
        console.log("成功发送请求");
        this.weizhifu = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //用户数
      .post("/api/admin/userstatistics", {})
      .then((response) => {
        console.log("成功发送请求");
        this.userstatistics = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //商城各分类商品数量 echarts
      .post("/api/admin/echone", {})
      .then((response) => {
        console.log("成功发送请求");
        this.echone = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    this.axios //订单发货数 echarts
      .post("/api/admin/echtwo", {})
      .then((response) => {
        console.log("成功发送请求");
        this.echtwo = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

       this.axios //下单的各分类商品数量 echarts
      .post("/api/admin/echthree", {})
      .then((response) => {
        console.log("成功发送请求");
        this.echthree = response.data.data;
      })
      .catch((error) => {
        console.log("发送请求失败：", error);
      });

    // goshipments内容 从路由的 query 中获取 selectedMenu
    const menu = this.$route.query.selectedMenu;
    if (menu) {
      this.selectedMenu = menu;
    }
  },
  components: {
    HeaderCart,
    HeaderSearch,
  },
  mounted() {//组件已渲染到页面后执行
    // 直接初始化时不要绘制图表，等待 selectedMenu 为 '2' 时再绘制
    this.$nextTick(() => {//确保DOM更新完成后执行某些操作
      if (this.selectedMenu === "2") {
        this.initChart();
      }
    });
  },
  watch: {
    //监听 selectedMenu 的变化
    selectedMenu(newVal) {
      //newVal 用来获取新值this.selectedMenu === '2'并基于新值做一些业务逻辑
      if (newVal === "2") {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
  },
  methods: {
    handleClick(index) {
      this.selectedMenu = index;
    },
    deleteUser() {
      // 清除sessionStorage中的管理员用户名
      sessionStorage.removeItem("adminName");
      // 重置adminName变量
      this.adminName = null;
    },
    Offshelf(index, row) {
      //下架
      let gid = row.gid;
      this.axios
        .post("/api/admin/Offshelf", { gid: gid })
        .then((res) => {
          alert(res.data.message);
          this.$router.go(0);
        })
        .catch((err) => {
          alert(err.message);
        });
    },
    editgoods(index, row) {
      console.log(this.accounts2[index]);
      this.$router.push({
        name: "admin_edit",
        params: { //在路由导航时传递参数
          goods: this.accounts2[index],
        },
      });
    },
    Onshelf(index, row) {
      //上架
      let gid = row.gid;
      this.axios
        .post("/api/admin/Onshelf", { gid: gid })
        .then((res) => {
          alert(res.data.message);
          this.$router.go(0);
        })
        .catch((err) => {
          alert(err.message);
        });
    },
    goshipments(index, row) { //(当前索引，当前行的数据)
      //去发货
      this.$router.push({
        name: "admin_goshipments",
        params: { //在路由导航时传递参数
          shipments: this.trueorder[index],
        },
      });
    },
    initChart() {
      // console.log('11:'+JSON.stringify(this.echone));     11:[{"a":8,"b":10,"c":10,"d":8}]
      const goodEcharts = this.$refs.goodEcharts;//获取图表容器元素,this.$refs获取引用的对象或组件实例
      const payEcharts = this.$refs.payEcharts;
      const orderEcharts = this.$refs.orderEcharts;
      if (!goodEcharts) {
        console.error("Chart container not found.");
        return;
      }
      const mygoodEcharts = echarts.init(goodEcharts);//初始化图表实例
      const mypayEcharts = echarts.init(payEcharts);
      const myorderEcharts = echarts.init(orderEcharts);
      const data = Object.values(this.echone[0]); //返回对象的所有值（即 a, b, c, d 对应的值），形成一个数组
      const option = {
        title: {
          text: "分类商品数",
        },
        tooltip: {},
        legend: {
          data: ["数量"],
        },
        xAxis: {
          data: ["香氛", "面霜", "爽肤水", "彩妆"],
        },
        yAxis: {
          type: "value",
          min: 0, // 设置最小值
          max: 20, // 设置最大值
          interval: 5, // 每刻度间隔
        },
        series: [
          {
            name: "数量",
            type: "bar",
            data: data,
          },
        ],
      };

      const option2 = {
  title: {
    text: '订单发货数据统计',
    subtext: '数量',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '数量',
      type: 'pie',
      radius: '50%',
      data: [
        { value: null, name: '已发货商品数' },
        { value: null, name: '未发货商品数' },
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};

      const option3 = {
           title: {
          text: "销售商品数",
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          left: "center",
        },
        series: [
          {
            name: "Access From",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              { value: null, name: "香氛" },
              { value: null, name: "面霜" },
              { value: null, name: "爽肤水" },
              { value: null, name: "彩妆" },
            ],
          },
        ],
      };


       // 根据 this.echthree 的数据更新 option2 中的 value
      option2.series[0].data.forEach((item, index) => {//item当前元素值
        const matched2 = this.echthree[index]; 
        if (matched2) {
          item.value = matched2.sendout;
        }
      });
      // 根据 this.echtwo 的数据更新 option3 中的 value
      option3.series[0].data.forEach((item, index) => {
        const matched = this.echtwo[index]; 
        if (matched) {
          item.value = matched.total;
        }
      });

      mygoodEcharts.setOption(option); //setOption()方法：设置或更新图表配置项
      mypayEcharts.setOption(option2);
      myorderEcharts.setOption(option3);
    },
  },
};
</script>

<style>
img {
  width: 60px;
  height: 60px;
}
#bigrow {
  width: 100%;
}
#col1 {
  width: 90%;
}
#col-row {
  width: 100%;
  height: 60px;
  background-color: #545c64;
  color: #fff;
  text-align: center;
  line-height: 60px;
}
#col {
  width: 90%;
}
#col2-row span {
  margin: auto;
}
#col2-row2 {
  height: 800px;
  width: 100%;
  background-size: cover;
  background-position: center;
  background-color: #f1f6fb;
}
#col2-row2-cardrow {
  width: 100%;
  height: 30%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
#col2-row3{
  width: 100%;
  height: 450px;
  padding-top:15px;
    background-color: #f1f6fb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
#col-card {
  width: 300px;
  height: 70%;
  border: 1px solid none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.32), 0 0 6px rgba(0, 0, 0, 0.24);
  border-radius: 4px;
}
#card1 {
  width: 100%;
  height: 10%;
  text-align: center;
}
#card2 {
  width: 100%;
  height: 90%;
  display: flex;
  align-items: center;
}
#card3 {
  width: 40%;
}
#card3 i {
  font-size: 66px;
  color: grey;
}
#card4 {
  width: 60%;
  font-size: 30px;
  color: red;
}
#echarts1{
  width: 50%;
  height: 100%; 
}
#echarts2{
  width: 25%;
  height: 100%; 
}
#echarts3{
  width: 25%;
  height: 100%; 
}
</style>